<template>
  <div class="panel-container patient-appointments">
    <div class="panel-header">
      <h2>我的预约</h2>
      <div class="header-actions">
        <!-- 搜索框 -->
        <div class="search-box">
          <input
              type="text"
              v-model="searchQuery"
              placeholder="搜索医生/科室/地点..."
              @keyup.enter="handleSearch"
          >
          <button class="search-button" @click="handleSearch">
            <i class="icon-search"></i>
          </button>
        </div>
        <button class="new-appointment-button" @click="newAppointment">
          <i class="icon-plus"></i> 新建预约
        </button>
      </div>
<!--      预约表单组件-->
      <AppointmentForm
          v-model:visible="showAppointmentForm"
          :appointment="currentAppointment"
          @submit="handleAppointmentSubmit"
      />

    </div>

    <div class="panel-content">
      <div class="appointment-filters">
        <div class="filter-group">
          <label>时间范围：</label>
          <select v-model="timeRangeFilter">
            <option value="today">今日预约 ({{ appointmentCounts.today }})</option>
            <option value="upcoming">即将到来 ({{ appointmentCounts.upcoming }})</option>
            <option value="past">历史记录 ({{ appointmentCounts.past }})</option>
            <option value="all">全部预约 ({{ appointmentCounts.all }})</option>
          </select>
        </div>
        <div class="filter-group">
          <label>状态筛选：</label>
          <select v-model="statusFilter">
            <option value="">全部状态 ({{ appointmentCounts.all }})</option>
            <option value="PENDING">待确认 ({{ appointmentCounts.pending }})</option>
            <option value="CONFIRMED">已预约 ({{ appointmentCounts.confirmed }})</option>
            <option value="COMPLETED">已完成 ({{ appointmentCounts.completed }})</option>
            <option value="CANCELED">已取消 ({{ appointmentCounts.canceled }})</option>
            <option value="CANCELLED">被取消 ({{ appointmentCounts.cancelled }})</option>
          </select>
        </div>
        <div class="filter-group">
          <label>问诊类型：</label>
          <select v-model="consultationTypeFilter">
            <option value="">全部类型 ({{ appointmentCounts.all }})</option>
            <option value="WESTERN">西医问诊 ({{ appointmentCounts.western }})</option>
            <option value="TRADITIONAL">中医辨证 ({{ appointmentCounts.tcm }})</option>
          </select>
        </div>

      </div>

      <div class="appointments-list">
        <div v-if="filteredAppointments.length === 0" class="empty-message">
          <template v-if="timeRangeFilter === 'today'">
            今日没有预约记录
          </template>
          <template v-else>
            暂无相关预约记录
          </template>
          <button class="empty-action-button" @click="newAppointment">
            立即预约
          </button>
        </div>
        <div v-else>
          <div class="appointment-item"
               v-for="appointment in filteredAppointments"
               :key="appointment.appointmentId"
               :class="appointment.status">
            <div class="appointment-info">
              <div class="appointment-time">
                <!-- 在日期区域最上方添加问诊类型 -->
                <!-- 问诊类型标签 - 放在最顶部 -->
                <div class="consultation-type-tag" style="margin-bottom: 25px;"
                     :class="appointment.consultationType.toLowerCase()"
                     :style="{ color: appointment.consultationType === 'WESTERN' ? 'blue' :
                     appointment.consultationType === 'TRADITIONAL' ? 'green' : 'inherit' }">
                  {{ getConsultationTypeText(appointment.consultationType) }}
                </div>

                <span class="date">{{ formatDate(appointment.appointmentDate) }}</span>
                <span class="time">{{ appointment.timeSlot }}</span>
              </div>
              <div class="appointment-details">
                <div class="medical-record">
                  <!-- 科室行 -->
                  <div class="record-row">
                    <span class="record-label">科室：</span>
                    <span class="record-value">{{ appointment.doctorDepartment }}</span>
                  </div>
                  <!-- 状态行 -->
                  <div class="record-row">
                    <span class="record-label">状态：</span>
                    <span
                        class="status-badge"
                        :class="'status-' + appointment.appointmentStatus"
                    >
                    {{ appointment.appointmentStatus }}
                    </span>
                  </div>
                  <!-- 症状描述行 -->
                  <div class="record-row">
                    <span class="record-label">症状描述：</span>
                    <span class="record-value symptom-text">{{appointment.symptoms}}</span>
                  </div>
                </div>

                <div class="detail-item" style="display: grid; grid-template-columns: auto 1fr; gap: 8px; align-items: center;">
                  <span class="label">医生：</span>
                  <span class="value">{{ appointment.doctorName }}</span>
                  <span class="label">职称：</span>
                  <span class="value">{{ appointment.doctorTitle }}</span>
                  <span class="label">电话：</span>
                  <span class="value">{{ appointment.doctorPhone }}</span>
                  <span class="label">地点：</span>
                  <span class="value">
                    {{ appointment.clinicLocation }}
                    {{ appointment.floorNumber }}
                    {{ appointment.roomNumber }}
                  </span>
                </div>
              </div>
            </div>
            <div class="appointment-actions">
              <!-- 找到原来的查看详情按钮，修改为 -->
              <button
                  class="action-button view"
                  @click="viewDetails(appointment)"
              >
                查看详情
              </button>

              <!-- 可取消状态显示取消按钮 -->
              <button
                  v-if="canCancel(appointment) || cancelledAppointments.has(appointment.appointmentId)"
                  :class="['action-button', cancelledAppointments.has(appointment.appointmentId) ? 'delete' : 'cancel']"
                  @click="cancelledAppointments.has(appointment.appointmentId) ? deleteAppointment(appointment.appointmentId) : cancelAppointment(appointment.appointmentId)"
              >
                {{ cancelledAppointments.has(appointment.appointmentId) ? '删除记录' : '取消预约' }}
              </button>
              <!-- 已完成状态显示删除按钮 -->
              <button v-if="appointment.appointmentStatus === '已完成' || appointment.appointmentStatus === '已取消'"
                      class="action-button delete"
                      @click="deleteAppointment(appointment.appointmentId)"
                      :disabled="loading">
                <span v-if="loading">删除中...</span>
                <span v-else>删除记录</span>
              </button>

              <button v-if="appointment.appointmentStatus === '已预约'"
                      class="action-button navigate"
                      @click="navigateToHospital(appointment)">
                导航到医院
              </button>
            </div>
          </div>
        </div>
      </div>

      <!--添加分页 -->
      <div class="pagination-container" v-if="filteredAppointments.length > 0">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :small="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @current-change="handlePageChange"
            @size-change="refreshAppointments"
        />
      </div>
    </div>
    <!-- 在template的最后添加 -->
      <el-dialog
          v-model="detailDialogVisible"
          :title="isEditing ? '编辑预约' : '预约详情'"
          width="600px"
      >
        <div class="detail-content" v-if="currentDetail">
          <!-- 基本信息部分 -->
          <div class="detail-section">
            <h3>基本信息</h3>
            <div class="detail-row" style="display: flex; justify-content: space-between; max-width: 400px; margin: 0
             auto;">
              <div class="detail-group">
                <span class="detail-label">预约ID：</span>
                <span>{{ currentDetail.appointmentId }}</span>
              </div>
              <div class="detail-group">
                <span class="detail-label">问诊类型：</span>
                <span>{{ getConsultationTypeText(currentDetail?.consultationType) }}</span>
              </div>
            </div>
            <div class="detail-row">
              <span class="detail-label">预约时间：</span>
              <template v-if="!isEditing">
                <span>{{ formatDate(currentDetail.appointmentDate) }} {{ currentDetail.timeSlot }}</span>
              </template>
              <template v-else>
                <div class="time-select-group">  <!-- 新增的包裹容器 -->
                  <el-date-picker
                      v-model="editData.appointmentDate"
                      type="date"
                      placeholder="选择日期"
                      value-format="YYYY-MM-DD"
                      :disabled-date="disabledPastDates"
                      class="date-picker"
                  />
                  <el-select
                      v-model="editData.timeSlot"
                      placeholder="选择时间段"
                      class="time-select"
                  >
                    <el-option
                        v-for="time in timeSlots"
                        :key="time"
                        :label="time"
                        :value="time"
                    />
                  </el-select>
                </div>
              </template>
            </div>

            <div class="detail-row">
              <span class="detail-label">当前状态：</span>
              <el-tag :type="getStatusTagType(currentDetail.appointmentStatus)">
                {{ currentDetail.appointmentStatus }}
              </el-tag>
            </div>
            <div class="detail-row">
              <span class="detail-label">症状描述：</span>
              <template v-if="!isEditing">
                <span class="symptom-text">{{ currentDetail.symptoms || '无' }}</span>
              </template>
              <template v-else>
                <el-input
                    v-model="editData.symptoms"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入症状描述"
                    show-word-limit
                    maxlength="500"
                />
              </template>
            </div>
          </div>

          <!-- 医生信息部分 - 保持只读 -->
          <div class="detail-section">
            <h3>医生信息</h3>
            <div class="detail-row">
              <span class="detail-label">医生ID：</span>
              <span>{{ currentDetail.doctorId }}</span>
            </div>
            <div class="detail-row">
              <span class="detail-label">医生姓名：</span>
              <span>{{ currentDetail.doctorName }}</span>
            </div>
            <div class="detail-row">
              <span class="detail-label">所属科室：</span>
              <span>{{ currentDetail.doctorDepartment }}</span>
            </div>
            <div class="detail-row">
              <span class="detail-label">医生职称：</span>
              <span>{{ currentDetail.doctorTitle }}</span>
            </div>
            <div class="detail-row">
              <span class="detail-label">联系电话：</span>
              <span>{{ currentDetail.doctorPhone }}</span>
            </div>
          </div>


          <!-- 就诊信息部分 -->
          <div class="detail-section">
            <h3>就诊信息</h3>
            <div class="detail-row">
              <span class="detail-label">就诊地点：</span>
              <span>{{ currentDetail.clinicLocation }} {{ currentDetail.floorNumber }}楼 {{ currentDetail.roomNumber }}室</span>
            </div>
          </div>
        </div>

        <template #footer>
          <el-button @click="handleDialogClose">关闭</el-button>
          <template v-if="!isEditing">
            <el-button
                v-if="currentDetail?.appointmentStatus === '待确认'"
                type="primary"
                @click="startEditing"
            >
              编辑预约
            </el-button>
          </template>
          <template v-else>
            <el-button @click="cancelEditing">取消</el-button>
            <el-button type="primary" @click="saveAppointment">保存</el-button>
          </template>
        </template>
      </el-dialog>
  </div>
</template>

<script setup>
import {ref, computed, onMounted, watch} from 'vue'
import { useRouter } from 'vue-router'
import AppointmentForm from "../form/AppointmentForm.vue"
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";

const router = useRouter()

// 响应式数据
const appointments = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10) // 每页显示10条
const total = ref(0) // 总记录数


const timeRangeFilter = ref('today')
const statusFilter = ref('')
const consultationTypeFilter = ref('') // 默认显示全部类型

const searchQuery = ref('') // 搜索关键词

const showAppointmentForm = ref(false)
const loading = ref(false)
const error = ref(null)

// 在JS中定义常量
const TimeRangeFilter = {
  ALL: 'all',
  TODAY: 'today',
  UPCOMING: 'upcoming',
  PAST: 'past'
}
// 计算属性
const appointmentCounts = computed(() => {
  const now = new Date();
  const todayStart = new Date(now);
  todayStart.setHours(0, 0, 0, 0);
  const todayEnd = new Date(now);
  todayEnd.setHours(23, 59, 59, 999);

  return {
    today: appointments.value.filter(app => {
      const appDate = new Date(app.appointmentDate);
      return appDate >= todayStart && appDate <= todayEnd;
    }).length,

    upcoming: appointments.value.filter(app => {
      const appDate = new Date(app.appointmentDate);
      return appDate > now;
    }).length,

    past: appointments.value.filter(app => {
      const appDate = new Date(app.appointmentDate);
      return appDate < todayStart;
    }).length,

    all: appointments.value.length,

    pending: appointments.value.filter(app =>
        app.appointmentStatus === '待确认'
    ).length,

    confirmed: appointments.value.filter(app =>
        app.appointmentStatus === '已预约'
    ).length,

    completed: appointments.value.filter(app =>
        app.appointmentStatus === '已完成'
    ).length,

    canceled: appointments.value.filter(app =>
        app.appointmentStatus === '已取消'
    ).length,
    cancelled:appointments.value.filter(app =>
        app.appointmentStatus ==='被取消'
    ).length,
    western: appointments.value.filter(app =>
        app.consultationType === '西医问诊'
    ).length,



    tcm: appointments.value.filter(app =>
        app.consultationType === '中医辨证'
    ).length
  };
});

// 计算筛选后的预约列表
const filteredAppointments = computed(() => {
  const now = new Date();
  const todayStart = new Date(now);
  todayStart.setHours(0, 0, 0, 0);
  const todayEnd = new Date(now);
  todayEnd.setHours(23, 59, 59, 999);

  return appointments.value.filter(appointment => {
    // 1. 时间范围筛选
    const appDate = new Date(appointment.appointmentDate);
    let timeMatch = true;

    if (timeRangeFilter.value === 'today') {
      timeMatch = appDate >= todayStart && appDate <= todayEnd;
    } else if (timeRangeFilter.value === 'upcoming') {
      timeMatch = appDate > now;
    } else if (timeRangeFilter.value === 'past') {
      timeMatch = appDate < todayStart;
    } else if (timeRangeFilter.value === 'all') {
      timeMatch = true;
    }

    // 2. 状态筛选 - 修正这里
    let statusMatch = true;
    if (statusFilter.value) {
      statusMatch = appointment.appointmentStatus ===
          (statusFilter.value === 'PENDING' ? '待确认' :
            statusFilter.value === 'CONFIRMED' ? '已预约' :
            statusFilter.value === 'COMPLETED' ? '已完成' :
            statusFilter.value === 'CANCELED' ? '已取消' :
            statusFilter.value === 'CANCELLED' ? '被取消' :
            statusFilter.value);
      }

    // 3. 问诊类型筛选 - 修正这里
    let typeMatch = true;
    if (consultationTypeFilter.value) {
      typeMatch = appointment.consultationType ===
          (consultationTypeFilter.value === 'WESTERN' ? '西医问诊' :
            consultationTypeFilter.value === 'TRADITIONAL' ? '中医辨证' :
            consultationTypeFilter.value);
    }

    // 4. 搜索查询
    let searchMatch = true;
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase();
      searchMatch =
          (appointment.doctorName && appointment.doctorName.toLowerCase().includes(query)) ||
          (appointment.doctorDepartment && appointment.doctorDepartment.toLowerCase().includes(query)) ||
          (appointment.clinicLocation && appointment.clinicLocation.toLowerCase().includes(query)) ||
          (appointment.symptoms && appointment.symptoms.toLowerCase().includes(query));
    }

    return timeMatch && statusMatch && typeMatch && searchMatch;
  });
});

// 添加一个将问诊类型英文转为中文的函数
const getConsultationTypeText = (type) => {
  const map = {
    'WESTERN': '西医问诊',
    'TRADITIONAL': '中医辨证'
  };
  return map[type] || type || '未知类型'; // 处理可能的null/undefined
}

// 计算当前页显示的数据
const pagedAppointments = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredAppointments.value.slice(start, end)
})

// 分页改变时触发
const handlePageChange = (newPage) => {
  currentPage.value = newPage
}


// 方法
// 获取预约数据
const refreshAppointments = async () => {
  loading.value = true;
  try {
    const queryParams = {
      timeRange: timeRangeFilter.value,
      status: statusFilter.value,
      consultationType: consultationTypeFilter.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }

    const response = await axios.get('http://localhost:6063/appointments/getAllAppointments', {
      params: queryParams
    });

    appointments.value = response.data?.data?.records || [];
    total.value = response.data?.data?.total || 0;

    // 打印完整的后端响应
    console.log('后端返回原始数据:', JSON.stringify(response.data, null, 2));

    // 增强空值保护
    appointments.value = (response.data?.data || []).map(item => ({
      appointmentId: item.appointmentId || '',
      patientId: item.patientId || '',
      patientName: item.patientName || '未知患者',
      patientAvatar: item.patientAvatar || '/default-avatar.png',
      doctorId: item.doctorId || '',
      doctorName: item.doctorName || '未知医生',
      doctorPhone: item.doctorPhone || '',
      doctorTitle: item.doctorTitle || '',
      doctorDepartment: item.doctorDepartment || '',
      appointmentDate: item.appointmentDate || '',
      timeSlot: item.timeSlot || '',
      clinicLocation: `${item.clinicLocation || ''} ${item.floorNumber || ''}${item.roomNumber || ''}`.trim(),
      appointmentStatus: item.appointmentStatus || '',
      symptoms: item.symptoms || '',
      consultationType: item.consultationType || ''
    }));

    // 打印处理后的数据
    console.log('处理后数据:', JSON.stringify(appointments.value, null, 2));
  } catch (error) {
    console.error('获取数据失败:', error);
    // 打印完整的错误响应（如果有）
    if (error.response) {
      console.error('错误响应数据:', JSON.stringify(error.response.data, null, 2));
      console.error('HTTP状态码:', error.response.status);
    }
    // 清空数据避免UI错误
    appointments.value = [];
  } finally {
    loading.value = false;
  }
};


// 搜索方法
const handleSearch = () => {
  // 计算属性会自动更新，这里只需确保数据刷新
  refreshAppointments()
}

// 当筛选条件变化时自动刷新
watch([timeRangeFilter, statusFilter, consultationTypeFilter,currentPage, pageSize], () => {
  refreshAppointments()
})



const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
}
// 查看详情
const detailDialogVisible = ref(false)
const currentDetail = ref(null)

const viewDetails = (appointment) => {
  currentDetail.value = appointment
  detailDialogVisible.value = true
}

const getStatusTagType = (status) => {
  const map = {
    '待确认': 'warning',
    '已预约': 'success',
    '已完成': '',
    '已取消': 'danger',
    '被取消': 'danger',
  }
  return map[status] || 'info'
}

// 当前正在编辑的预约数据
const currentAppointment = ref(null)

// 判断是否可以取消
const canCancel = (appointment) => {
  return ['待确认'].includes(appointment.appointmentStatus)
}

// 取消预约
const cancelledAppointments = ref(new Set()); // 存储已取消的预约ID

// 在 <script setup> 部分修改 cancelAppointment 方法
const cancelAppointment = async (id) => {
  try {
    await ElMessageBox.confirm('确定要取消此预约吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 调用取消预约API
    const response = await axios.put(`http://localhost:6063/appointments/cancel/${id}`);
    if (response.data.code === 200) {
      ElMessage.success('预约已取消');
      // 刷新预约列表
      await refreshAppointments();
    } else {
      ElMessage.error('取消失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消失败: ' + error.message);
    }
  }
};

// 删除预约记录
const deleteAppointment = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除此记录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    loading.value = true;

    const response = await axios.delete(`http://localhost:6063/appointments/deleteAppointment`, {
      params: { appointmentId: id }
    });

    // 仅打印被删除的数据
    console.log('已删除的数据:', response.data.data);

    if (response.data.code === 200) {
      ElMessage.success('删除成功');
      await refreshAppointments();
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  } finally {
    loading.value = false;
  }
};

// 新建预约
const newAppointment = () => {
  currentAppointment.value = {
    appointmentId: null,
    clinicLocation: '',
    floorNumber: '',
    roomNumber: '',
    appointmentTime: '',
    // 其他字段...
  }
  showAppointmentForm.value = true
}

// 编辑预约
const isEditing = ref(false)
const editData = ref({})
const timeSlots = ref([
  '08:00-09:00', '09:00-10:00', '10:00-11:00',
  '14:00-15:00', '15:00-16:00', '16:00-17:00'
])
const startEditing = () => {
  isEditing.value = true
  editData.value = {
    appointmentDate: currentDetail.value.appointmentDate,
    timeSlot: currentDetail.value.timeSlot,
  }
}
const cancelEditing = () => {
  isEditing.value = false
  editData.value = {}
}
// 在script setup部分添加/修改以下代码
const saveAppointment = async () => {
  try {
    loading.value = true;

    const requestData = {
      appointmentId: currentDetail.value.appointmentId,
      doctorId: currentDetail.value.doctorId, // 确保包含医生ID
      appointmentDate: editData.value.appointmentDate,
      timeSlot: editData.value.timeSlot,
      symptoms: editData.value.symptoms || currentDetail.value.symptoms,
      // 添加其他必要字段
    };

    const response = await axios.put(
        'http://localhost:6063/appointments/updateAppointment',
        requestData
    );

    if (response.data.code === 200) {
      ElMessage.success('预约修改成功');

      // 更新当前显示的详情
      Object.assign(currentDetail.value, {
        appointmentDate: editData.value.appointmentDate,
        timeSlot: editData.value.timeSlot,
        symptoms: editData.value.symptoms,
        // 其他需要更新的字段
      });

      // 更新列表中的对应记录（仅当医生ID相同时）
      const index = appointments.value.findIndex(
          a => a.appointmentId === currentDetail.value.appointmentId &&
              a.doctorId === currentDetail.value.doctorId
      );

      if (index !== -1) {
        appointments.value[index] = {
          ...appointments.value[index],
          ...requestData
        };
      } else {
        // 如果医生ID不同，可以添加到列表开头（根据业务需求调整）
        appointments.value.unshift({
          ...currentDetail.value,
          ...requestData
        });
      }

      isEditing.value = false;
    }
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error(`保存失败: ${error.response?.data?.message || error.message}`);
  } finally {
    loading.value = false;
  }
};





const handleDialogClose = () => {
  if (isEditing.value) {
    ElMessageBox.confirm('您有未保存的修改，确定要关闭吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      isEditing.value = false
      detailDialogVisible.value = false
    })
  } else {
    detailDialogVisible.value = false
  }
}
// 禁用过去的日期
const disabledPastDates = (time) => {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

const handleAppointmentSubmit = (updatedAppointment) => {
  if (updatedAppointment.appointmentId) {
    // 更新现有记录
    const index = appointments.value.findIndex(
        a => a.appointmentId === updatedAppointment.appointmentId
    );
    if (index !== -1) {
      appointments.value[index] = updatedAppointment;
    }
  } else {
    // 新增记录（如果有新增功能）
    const newId = Math.max(...appointments.value.map(a => a.appointmentId), 0) + 1;
    appointments.value.push({
      appointmentId: newId,
      ...updatedAppointment
    });
  }

  showAppointmentForm.value = false;
  ElMessage.success('操作成功');
};

const navigateToHospital = (appointment) => {
  alert(`将导航到: ${appointment.location}`)
}

// 初始化
onMounted(() => {
  refreshAppointments()

})
</script>
<style scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.time-select-group {
  display: flex;
  align-items: center; /* 垂直居中 */
  gap: 10px; /* 两个选择器之间的间距 */
}

.date-picker {
  flex: 1; /* 日期选择器占据剩余空间 */
  min-width: 180px; /* 最小宽度 */
}

.time-select {
  flex: 0 0 150px; /* 固定宽度 */
}


.medical-record {
  font-family: 'Microsoft YaHei', sans-serif;
  max-width: 600px;
  margin: 0 auto;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 8px;
}

.record-row {
  display: flex;
  margin-bottom: 12px;
  align-items: flex-start;
}

.record-label {
  flex: 0 0 100px;
  text-align: right;
  padding-right: 15px;
  color: #666;
  font-weight: bold;
}

.record-value {
  flex: 1;
  text-align: left;
  color: #333;
}

.status-badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.9em;
  /* 自动宽度 */
  width: fit-content;
  /* 去除多余空白 */
  margin: 0;
  line-height: 1.3;
}

/* 不同状态的颜色方案 */
.status-待确认 {
  background-color: #FFF3CD;
  color: #856404;
  border: 1px solid #FFEEBA;
}

.status-已预约 {
  background-color: #D4EDDA;
  color: #155724;
  border: 1px solid #C3E6CB;
}

.status-已取消 {
  background-color: #F8D7DA;
  color: #721C24;
  border: 1px solid #F5C6CB;
}

.status-已完成 {
  background-color: #E2E3E5;
  color: #383D41;
  border: 1px solid #D6D8DB;
}

.status-被取消 {
  background-color: #F8D7DA;  /* 浅红色背景，比已完成状态略暖 */
  color: #721C24;            /* 深红色文字，确保可读性 */
  border: 1px solid #F5C6CB; /* 比背景深1度的边框 */
  position: relative;        /* 为特殊效果预留 */
}
.symptom-text {
  white-space: pre-wrap;
  line-height: 1.6;
  background: #e9f5ff;
  padding: 8px 12px;
  border-radius: 6px;
  border-left: 3px solid #1890ff;
}

/* 在style部分添加 */
.detail-content {
  line-height: 1.8;
}

.detail-section {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.detail-section h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

.detail-row {
  display: flex;          /* 启用弹性布局 */
  align-items: baseline;  /* 基线对齐 */
  margin-bottom: 8px;     /* 行间距 */
}

.label {
  flex: 0 0 80px;         /* 固定标签宽度 */
  text-align: right;      /* 标签右对齐 */
  padding-right: 12px;    /* 标签与值的间距 */
  color: #666;
  font-weight: bold;
}

/* 新增搜索框样式 */
.search-box {
  /* 定位和布局 */
  position: absolute;  /* 绝对定位脱离文档流 */
  left: 20px;         /* 距离左侧20px */
  top: 20px;          /* 距离顶部20px */

  /* 样式设计 */
  display: flex;
  align-items: center;
  width: 280px;       /* 固定宽度 */
  height: 40px;       /* 固定高度 */
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 20px; /* 圆形边框 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 轻微阴影 */
  overflow: hidden;
  transition: all 0.3s;
  z-index: 10;        /* 确保在其他元素上方 */
}


.search-box:hover {
  border-color: #c0c4cc;
}

/* 输入框样式 */
.search-box input {
  flex: 1;
  border: none;
  padding: 0 15px;
  height: 100%;
  outline: none;
  font-size: 14px;
}

/* 搜索按钮样式 */
.search-button {
  width: 40px;
  height: 100%;
  border: none;
  background: transparent;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  transition: all 0.3s;
}


.search-button:hover {
  color: #409eff;
  background: #ecf5ff;
}

.icon-search {
  font-size: 14px;
}
/**/
.patient-appointments {
  font-family: 'Helvetica Neue', Arial, sans-serif;
  color: #333;
  max-width: 1000px;
  margin: 0 auto;
}

.panel-header {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.panel-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
  flex-grow: 1;
}

.new-appointment-button {
  margin-right: 10px;
  color: #fff;
  background-color: #409eff;
  border: 1px solid #409eff;
}

.new-appointment-button:hover {
  background-color: #66b1ff;
}

.icon-arrow-left, .icon-refresh, .icon-plus {
  margin-right: 5px;
}

.appointment-filters {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding: 0 20px;
}

.filter-group {
  display: flex;
  align-items: center;
}

.filter-group label {
  margin-right: 10px;
  font-size: 14px;
  color: #666;
}

.filter-group select {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  color: #606266;
  min-width: 120px;
}

.filter-group select option::after {
  content: attr(data-count);
  float: right;
  color: #999;
  font-size: 0.9em;
}

.appointment-list {
  padding: 0 20px;
}

.appointment-item {
  padding: 20px;
  margin-bottom: 15px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  border-left: 4px solid #3b82f6;
}

.appointment-item.pending {
  border-left-color: #f59e0b;
}

.appointment-item.confirmed {
  border-left-color: #10b981;
}

.appointment-item.completed {
  border-left-color: #64748b;
}

.appointment-item.canceled {
  border-left-color: #ef4444;
  opacity: 0.7;
}

.appointment-info {
  display: flex;
  gap: 30px;
}

.appointment-time {
  text-align: center;
  padding: 30px 20px; /* 增加内边距 */
  background: #f9f9f9;
  border-radius: 8px;
  max-width: 200px;
  margin: 0 auto;
}

.appointment-time .date {
  font-size: 16px;
  font-weight: bold;
  color: #1e293b;
}

.appointment-time .time {
  font-size: 24px;
  font-weight: bold;
  color: #3b82f6;
  margin-top: 5px;
}

.appointment-item.pending .appointment-time .time {
  color: #f59e0b;
}

.appointment-item.confirmed .appointment-time .time {
  color: #10b981;
}

.appointment-details {
  flex-grow: 1;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

/* 核心对齐方案 */
.detail-item {
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  line-height: 1.6;
}

.label {
  color: #666;
  min-width: 60px;
}

.value {
  flex: 1;                /* 自动填充剩余空间 */
  text-align: left;       /* 强制左对齐 */
}


.appointment-item.pending .status-badge {
  background-color: #fef3c7;
  color: #92400e;
}

.appointment-item.confirmed .status-badge {
  background-color: #d1fae5;
  color: #065f46;
}

.appointment-item.completed .status-badge {
  background-color: #e2e8f0;
  color: #334155;
}

.appointment-item.canceled .status-badge {
  background-color: #fee2e2;
  color: #991b1b;
}

.appointment-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
  gap: 10px;
}

.action-button {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  border: 1px solid transparent;
  transition: all 0.2s;
}

.action-button.view {
  background-color: #e0e7ff;
  color: #4f46e5;
  border-color: #c7d2fe;
}

.action-button.view:hover {
  background-color: #c7d2fe;
}

.action-button.cancel {
  background-color: #fee2e2;
  color: #ef4444;
  border-color: #fecaca;
}

.action-button.cancel:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.action-button.cancel:hover {
  background-color: #fecaca;
}
/*删除按钮样式*/
.action-button.delete {
  background-color: #fee2e2;
  color: #ef4444;
  border-color: #fecaca;
}

.action-button.delete:hover {
  background-color: #fecaca;
}

.action-button.edit {
  background-color: #e0f2fe;
  color: #0369a1;
  border-color: #bae6fd;
}

.action-button.edit:hover {
  background-color: #bae6fd;
}


.action-button.navigate {
  background-color: #ecfdf5;
  color: #059669;
  border-color: #a7f3d0;
}

.action-button.navigate:hover {
  background-color: #a7f3d0;
}

.empty-message {
  text-align: center;
  padding: 60px 20px;
  color: #999;
  font-size: 16px;
  background-color: #f8fafc;
  border-radius: 8px;
  margin-top: 20px;
}

.empty-action-button {
  display: block;
  margin: 20px auto 0;
  padding: 10px 20px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.empty-action-button:hover {
  background-color: #66b1ff;
}

@media (max-width: 768px) {
  .header-actions {
    flex-wrap: wrap;
    gap: 10px;
  }
  .search-box {
    order: 1;
    width: 100%;
    margin-right: 0;
  }
  .search-box input {
    width: 100%;
  }
  .new-appointment-button {
    order: 2;
  }

  .appointment-filters {
    flex-direction: column;
    gap: 10px;
  }

  .appointment-info {
    flex-direction: column;
    gap: 15px;
  }

  .appointment-time {
    flex-direction: row;
    justify-content: flex-start;
    gap: 15px;
    min-width: auto;
  }

  .appointment-time .time {
    margin-top: 0;
  }

  .appointment-details {
    grid-template-columns: 1fr;
  }

  .appointment-actions {
    justify-content: flex-start;
    flex-wrap: wrap;
  }

  .panel-header {
    flex-wrap: wrap;
    gap: 10px;
  }

  .panel-header h2 {
    order: 1;
    width: 100%;
    margin-top: 10px;
  }
}
</style>
